#
#  Copyright 2022 The Open Islands Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
from pyoi.session import Session
from pyoi.constant import DatasetFormat, DataStructure
from pyoi.types import DataIO, DataSchema
from pyoi.util import UriUtils
from pyoi.util.log_utils import getLogger

LOGGER = getLogger()


class ReaderParam:
    def __init__(self, uri: str, format: str, include_header: bool = None, delimiter: str = None,
                 num_partitions: int = None, add_sequence_id: bool = False, random_sequence_id: bool = False):
        self.uri = uri
        self.format = DatasetFormat[format.upper()]
        self.include_header = include_header
        self.delimiter = delimiter
        # todo: should be set default by server
        self.num_partitions = num_partitions if num_partitions else 4
        self.add_sequence_id = add_sequence_id
        self.random_sequence_id = random_sequence_id
        self._check_param()

    def _check_param(self):
        assert self.uri
        assert self.format
        if self.format == DatasetFormat.CSV:
            assert self.include_header is not None
            assert self.delimiter


class Reader:
    def __init__(self):
        pass

    def run(self, job_type, param, datas, models):
        my_param = ReaderParam(**param)
        dataio = DataIO(uri=UriUtils.fill_abs_file_uri(my_param.uri), format=my_param.format,
                        num_partitions=my_param.num_partitions)

        dataio.schema = DataSchema()
        dataio.schema.include_header = my_param.include_header
        dataio.schema.delimiter = my_param.delimiter

        rdd, schema = Session.get().create_context(DataStructure.SPARK_RDD).load_text(dataio)
        schema.update_metadata(
            {"add_sequence_id": my_param.add_sequence_id, "random_sequence_id": my_param.random_sequence_id})
        LOGGER.info(f"load data {schema} in memory success")
        dataio.data = rdd
        dataio.schema = schema
        return [dataio], []
